﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using Cinemachine;

//枪械控制器，实现瞄准镜跟随相机；提供瞄准镜的动画控制；子弹管理、开火控制
public class GunController : MonoBehaviour
{
    //相机控制器
    public CinemachineVirtualCamera cinemachineVirtualCamera;
    //瞄准镜目标点动画控制器
    public Animator gunSightAnimator;
    //自身动画控制器
    public Animator gunAnimator;
    //开火声音
    public AudioSource fireAudio;
    //相机位置
    public Transform cameraPosition;
    //子弹预制
    public GameObject bulletPrefab;
    //枪口火光预设
    public GameObject boomPrefab;
    //枪口位置
    public Transform muzzlePosition;

    //子弹text
    public Text bulletNumText;
    //弹夹容量
    public int clipSize;
    //当前弹夹子弹量
    int bulletNum;
    //是否就绪
    bool readyToFire = true;
    //上膛声音
    public AudioSource chargeAutio;
    //没有子弹声音
    public AudioSource noBulletAutio;
    //换弹夹声音
    public AudioSource reloadAudio;
    // Start is called before the first frame update
    void Start()
    {
        bulletNum = clipSize;
        bulletNumText.text = "子弹：" + bulletNum;
    }

    // Update is called once per frame
    void Update()
    {
        //跟随相机的X、Y坐标。
        transform.position = new Vector3(cameraPosition.position.x, cameraPosition.position.y, transform.position.z);
    }

    //变焦
    public void zoom(float zoomNum)
    {
        cinemachineVirtualCamera.m_Lens.OrthographicSize = 2 * zoomNum;
        transform.localScale = new Vector3(1, 1, 0) * zoomNum;
    }

    //开枪
    public void fire()
    {
        if(readyToFire)
        {
            if (bulletNum > 0) {
                readyToFire = false;
                bulletNum--;
                bulletNumText.text = "子弹：" + bulletNum;
                //生成火光
                Instantiate(boomPrefab, muzzlePosition.transform.position, muzzlePosition.rotation);
                //生成子弹
                Instantiate(bulletPrefab, muzzlePosition.transform.position, muzzlePosition.rotation);
                //触发开火动画
                gunSightAnimator.SetTrigger("shoot");
                //触发开火声音
                fireAudio.Play();
            }
            else
            {
                noBulletAutio.Play();
            }
        }

    }

    //上膛
    public void charge()
    {
        gunAnimator.SetTrigger("charge");
        chargeAutio.Play();
    }

    //上膛完成回调
    public void chargeReady()
    {
        readyToFire = true;
    }

    //换弹夹
    public void reload() {
        reloadAudio.Play();
        gunAnimator.SetTrigger("reload");
    }

    //换弹完成
    public void reloadOver()
    {
        bulletNum = clipSize;
        bulletNumText.text = "子弹：" + bulletNum;
    }
}
